package com.usian.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.usian.config.RedisClient;
import com.usian.mapper.TbContentCategoryMapper;
import com.usian.mapper.TbContentMapper;
import com.usian.pojo.TbContent;
import com.usian.pojo.TbContentCategory;
import com.usian.pojo.TbContentCategoryExample;
import com.usian.pojo.TbContentExample;
import com.usian.service.ContentService;
import com.usian.utils.AdNode;
import com.usian.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class ContentServiceImpl implements ContentService {

    @Autowired
    private TbContentCategoryMapper tbContentCategoryMapper;

    @Autowired
    private TbContentMapper tbContentMapper;
    @Autowired
    private RedisClient redisClient;

    @Value("${AD_CATEGORY_ID}")
    private Long AD_CATEGORY_ID;

    @Value("${AD_HEIGHT}")
    private Integer AD_HEIGHT;

    @Value("${AD_WIDTH}")
    private Integer AD_WIDTH;

    @Value("${AD_HEIGHTB}")
    private Integer AD_HEIGHTB;

    @Value("${AD_WIDTHB}")
    private Integer AD_WIDTHB;

    @Value("${PORTAL_AD_KEY}")
    private String  PORTAL_AD_KEY;

    @Override
    public List<TbContentCategory> selectContentCategoryByParentId(Long id) {
        TbContentCategoryExample example = new TbContentCategoryExample();
        TbContentCategoryExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(id);
        criteria.andStatusEqualTo(1);
        List<TbContentCategory> list = tbContentCategoryMapper.selectByExample(example);
        return list;
    }

    public  Integer insertContentCategory(Long parentId, String name){

        //1：保存咱们叶子数据
        TbContentCategory content = new TbContentCategory();
        content.setParentId(parentId);
        content.setName(name);
        content.setSortOrder(1);
        content.setStatus(1);
        content.setCreated(new Date());
        content.setUpdated(new Date());
        content.setIsParent(false); //默认儿子
        int num = tbContentCategoryMapper.insertSelective(content);

        //2:根据叶子节点parentId 查父节点 判断是不是父节点  不是  改成父节点

        //2.1:根据叶子节点parentId 查父节点
        TbContentCategoryExample example =new TbContentCategoryExample();
        TbContentCategoryExample.Criteria criteria =example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        TbContentCategory category = tbContentCategoryMapper.selectByPrimaryKey(parentId);

        //2.2:断是不是父节点  不是  改成父节点
        if(!category.getIsParent()){
            category.setIsParent(true);
            category.setUpdated(new Date());
            int num1 = tbContentCategoryMapper.updateByPrimaryKeySelective(category);
        }


        return num;
    }


    public Integer deleteContentCategoryById(Long categoryId){

        //1:判断传递过来是否父节点
        TbContentCategory category = tbContentCategoryMapper.selectByPrimaryKey(categoryId);


        //2:不是父节点 逻辑删除修改 2  是  不能删除 返回一个0
        if(category.getIsParent()){
            return 0;
        }
        TbContentCategory contentCategory =new TbContentCategory();
        contentCategory.setId(categoryId);
        contentCategory.setStatus(2);
        contentCategory.setUpdated(new Date());
        tbContentCategoryMapper.updateByPrimaryKeySelective(contentCategory);

        //3:判断删完的父节点 parentId 下边有没有子节点  有  什么不操作    没有  父节点 parentId变成子节点


        //根据父节点id 查询 下面还有多少个子节点
        TbContentCategoryExample example =new TbContentCategoryExample();
        TbContentCategoryExample.Criteria criteria =example.createCriteria();
        criteria.andParentIdEqualTo(category.getParentId());
        criteria.andStatusEqualTo(1);
        List<TbContentCategory> list = tbContentCategoryMapper.selectByExample(example);

        if(list.size()==0){
            TbContentCategory parenttbContentCategory = new TbContentCategory();
            parenttbContentCategory.setId(category.getParentId());
            parenttbContentCategory.setIsParent(false);
            parenttbContentCategory.setUpdated(new Date());
            tbContentCategoryMapper.updateByPrimaryKeySelective(parenttbContentCategory);
        }

        return 200;
    }


    /**
     *
     * 分页查询商品内容
     *
     * @param categoryId
     * @param page
     * @param rows
     * @return
     */
    public PageResult selectTbContentAllByCategoryId(Long categoryId, Integer page, Integer rows){

        PageHelper.startPage(page,rows);

        TbContentExample example =new TbContentExample();
        TbContentExample.Criteria criteria =example.createCriteria();
        criteria.andCategoryIdEqualTo(categoryId);
        List<TbContent> list = tbContentMapper.selectByExample(example);

        PageInfo<TbContent> pageInfo =new PageInfo<>(list);

        PageResult pageResult =new PageResult();
        pageResult.setPageIndex(pageInfo.getPageNum());
        pageResult.setTotalPage(pageInfo.getPages());
        pageResult.setResult(pageInfo.getList());

        return pageResult;
    }


    /**
     * 保存商品内容
     *
     * @param tbContent
     * @return
     */
    public Integer insertTbContent(TbContent tbContent){
        tbContent.setCreated(new Date());
        tbContent.setUpdated(new Date());
        int num = tbContentMapper.insertSelective(tbContent);

        //删除缓存的key
        redisClient.del(PORTAL_AD_KEY);
        return num;
    }

    /**
     * 根据id删除商品内容分类
     *
     * @param ids
     * @return
     */
    public Integer deleteContentByIds(Long ids){
        //删除缓存的key
        redisClient.del(PORTAL_AD_KEY);
        return tbContentMapper.deleteByPrimaryKey(ids);
    }

    @Override
    public List<AdNode> selectFrontendContentByAD() {


        //优先从redis取，取不到从数据库查
        List<AdNode> adNodeListRedis = (List<AdNode>)redisClient.hget(PORTAL_AD_KEY,AD_CATEGORY_ID.toString());
        if(adNodeListRedis!=null){
            return adNodeListRedis;
        }

        TbContentExample tbContentExample = new TbContentExample();
        TbContentExample.Criteria criteria = tbContentExample.createCriteria();
        criteria.andCategoryIdEqualTo(AD_CATEGORY_ID);
        List<TbContent> tbContentList =
                tbContentMapper.selectByExample(tbContentExample);

        List<AdNode> adNodeList = new ArrayList<AdNode>();

        Long cateGoryId=0L;
        for (TbContent tbContent : tbContentList){
            cateGoryId =tbContent.getCategoryId();
            AdNode adNode = new AdNode();
            adNode.setSrc(tbContent.getPic());
            adNode.setSrcB(tbContent.getPic2());
            adNode.setHref(tbContent.getUrl());
            adNode.setHeight(AD_HEIGHT);
            adNode.setWidth(AD_WIDTH);
            adNode.setHeightB(AD_HEIGHTB);
            adNode.setWidthB(AD_WIDTHB);
            adNodeList.add(adNode);
        }

        //存redis
        redisClient.hset(PORTAL_AD_KEY,cateGoryId.toString(),adNodeList);
        return adNodeList;
    }
}
